package com.yuanfeng.action.front.address.dao;
import com.yuanfeng.pojo.Address;
import com.yuanfeng.util.WebUtil;
import java.util.List;
import java.util.UUID;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * 收货地址的dao实现类
 * @author yuanfeng
 *
 */
public class AddressDaoImpl extends HibernateDaoSupport implements AddressDao {

	/**
	 * 根据uiserId查询地址
	 * @param userId
	 * @return
	 */
	public List<Address> queryAddress(final String userId) {

		List<Address> addresses =  (List<Address>) this.getHibernateTemplate().executeFind(new HibernateCallback<List<Address>>() {
			@Override
			public List<Address> doInHibernate(Session session) throws HibernateException {
				String hql = "from Address where userid=? order by mktime desc";
				Query query = session.createQuery(hql);
				query.setParameter(0, userId);
				return query.list();
			}
		});
		return addresses;
	}

	/**
	 * 增加地址
	 * @param addr
	 * @return
	 */
	public Address add(Address addr) {

		Address address = new Address();
		address.setId(UUID.randomUUID().toString().replace("-", ""));
		address.setName(addr.getName());
		address.setPhone(addr.getPhone());
		address.setZip(addr.getZip());
		address.setUserid(addr.getUserid());
		address.setMktime(WebUtil.getDateStr());
		this.getHibernateTemplate().save(address);
		this.getHibernateTemplate().flush();
		return address;
	}

	/**
	 * 改变默认的地址
	 * @param addr
	 */
	public void changeToDefault( Address addr) {

        List<Address> addrList1 = this.getHibernateTemplate().find("from Address where userid=?", addr.getUserid());
		addrList1.get(0).setDft("0");
		this.getHibernateTemplate().update(addrList1.get(0));
		//通过主键得到持久化对象
		Address address  = this.getHibernateTemplate().get(Address.class,addr.getId());
		address.setDft("1");
		this.getHibernateTemplate().update(address);
	}
	/**
	 * 删除地址
	 * @param addr
	 */
	public void delete(Address addr) {
		Address address = this.getHibernateTemplate().get(Address.class, addr.getId());
		this.getHibernateTemplate().delete(address);
		this.getHibernateTemplate().flush();
		this.getHibernateTemplate().clear();
	}
}
